package main

import (
	"database/sql"
	"fmt"
	"github.com/ArthurHlt/go-eureka-client/eureka"
	"github.com/gin-gonic/gin"
	_ "github.com/go-sql-driver/mysql"
	"net/http"
	"strconv"
)

//import "net/http"

type Result struct {
	Code    int         `json:"code"`
	Data    interface{} `json:"data"`
	Message string      `json:"message"`
}

type User struct {
	Id     int32  `json:"id"`
	Info   string `json:"info"`
	Status string `json:"status"`
	Money  int32  `json:"money"`
}

var db *sql.DB

func initDb() *sql.DB {
	db, error := sql.Open("mysql", "root:@tcp(127.0.0.1:3306)/TestDb?parseTime=true")
	if error != nil {
		panic(error)
	}
	return db
}

func init() {
	db = initDb()
}

func main() {
	r := gin.Default()
	r.GET("/ping", func(context *gin.Context) {
		context.JSON(200, Result{Code: 200, Data: User{Info: "byref"}, Message: "query success"})
	})

	r.GET("/user", func(context *gin.Context) {
		var users []User
		query, _ := db.Query("SELECT * FROM `User` limit 10")
		for query.Next() {
			user := User{}
			query.Scan(&user.Id, &user.Info, &user.Status, &user.Money)
			users = append(users, user)
		}
		query.Close()
		context.JSON(200, Result{Code: 200, Data: users})
	})

	r.DELETE("/user/:id", func(context *gin.Context) {
		id := context.Param("id")
		intId,_ := strconv.Atoi(id)
		exec, err := db.Exec("delete from `User` where id = ?", intId)
		if err != nil {
			context.JSON(http.StatusInternalServerError, Result{Code: 500, Message: "异常"})
			return
		}
		affected, err := exec.RowsAffected()
		context.JSON(200, Result{Code: 200, Message: "删除成功:" + strconv.FormatInt(affected,10)})
	})

	defer db.Close()

	client := eureka.NewClient([]string{
		"https://admin:password@dev-eureka.superdxp.com/eureka", //From a spring boot based eureka server
		// add others servers here
	})
	instance := eureka.NewInstanceInfo("go-app", "go-app", "localhost", 8080, 30, false) //Create a new instance to register
	instance.Metadata = &eureka.MetaData{
		Map: make(map[string]string),
	}
	instance.Metadata.Map["foo"] = "bar" //add metadata for example
	client.RegisterInstance("go-app", instance) // Register new instance in your eureka(s)
	applications, _ := client.GetApplications() // Retrieves all applications from eureka server(s)
	fmt.Print(applications)
	client.GetApplication(instance.App) // retrieve the application "test"
	client.GetInstance(instance.App, instance.HostName) // retrieve the instance from "test.com" inside "test"" app
	client.SendHeartbeat(instance.App, instance.HostName)

	r.Run()
}
